import { Button, Col, Form, Input, Row, Select, Spin } from 'antd';
import React, { useEffect } from 'react';
// @ts-ignore
import { TJModel } from '@/pages/ETrade/components';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import dayjs from 'dayjs';
import type { Dispatch } from 'redux';
import { connect } from 'umi';
import styles from './index.less';
import { validateNoSpaces } from '../../../helper';

const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 17 },
  },
};

interface PlanProps {
  treeData: any[];
  state: {
    addVisible: boolean;
    modelTitle: string;
  } & Partial<FieldType>;
  onCancelAddVisible: () => void;
  onFinish: (values: any) => void;
  buttonPermissions: any;
  list: any[];
  editValue?: any;
  windowConfigs: any;
  configLoading: boolean;
  dispatch: Dispatch;
}

type FieldType = {
  windowName?: string;
  stationIds?: string[];
  minPrice?: string;
  maxPrice?: string;
  minQuantity?: string;
  maxQuantity?: string;
  totalDelisted?: string;
};

const Plan: React.FC<PlanProps> = ({
  treeData,
  state,
  onCancelAddVisible,
  onFinish,
  buttonPermissions,
  windowConfigs,
  configLoading,
  list,
  editValue,
  dispatch,
}) => {
  const { modelTitle, stationIds } = state;
  const [form] = Form.useForm();

  useEffect(() => {
    if (modelTitle === '编辑') {
      form.setFieldsValue({
        priceRange: '-',
        quantityRange: '-',
      });
    }
  }, [modelTitle]);

  useEffect(() => {
    if (Object.keys(editValue).length > 0) {
      const [minPrice, maxPrice] = editValue.priceRange?.split('~');
      const [minQuantity, maxQuantity] = editValue.quantityRange?.split('~');
      const newData = {
        scenarioName: editValue.windowId,
        stationIds: [editValue.marketId],
        minPrice,
        maxPrice,
        minQuantity,
        maxQuantity,
        totalDelisted: editValue.totalDelisted,
      };
      form.setFieldsValue(newData);
    } else {
      form.resetFields();
      form.setFieldsValue({
        stationIds,
        marketDate: '-',
        reportDate: '-',
      });
    }
  }, [editValue, form, state.addVisible]);

  useEffect(() => {
    if (windowConfigs) {
      form.setFieldsValue({
        marketDate: windowConfigs?.startMarkDate + '~' + windowConfigs?.endMarkDate || '-',
        reportDate:
          dayjs(windowConfigs.reportDate).format('YYYYMMDD') +
            ' ' +
            windowConfigs?.startReportTime +
            '~' +
            windowConfigs?.endReportTime || '-',
      });
    }
  }, [windowConfigs]);

  const handleFinish = (values: any) => {
    if (editValue?.id) {
      values.id = editValue.id;
    }
    onFinish(values);
  };

  const Content = () => {
    return (
      <div>
        {modelTitle === '新增' ? (
          <Spin spinning={configLoading}>
            <div>
              <Form.Item<FieldType>
                label="窗口名称"
                name="scenarioName"
                rules={[{ required: true, message: '窗口名称必填!' }]}
              >
                <Select
                  placeholder="请选择窗口名称"
                  allowClear
                  onChange={(value: number) => {
                    if (value) {
                      dispatch({
                        type: 'ListingTransactionDeclaration/fetchQueryWindow',
                        payload: value,
                      });
                    }
                  }}
                >
                  {list.map((item) => {
                    return (
                      <Option value={item.windowId} key={item.windowId}>
                        {item.windowName}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item<FieldType>
                label="交易单元"
                name="stationIds"
                rules={[{ required: true, message: '交易单元必填!' }]}
              >
                <TjMarketingUnit
                  treeData={treeData}
                  onChange={(ids: any) => {
                    form.setFieldsValue({ stationIds: ids });
                  }}
                />
              </Form.Item>
              <Form.Item<FieldType>
                name="marketDate"
                label={<span style={{ marginLeft: 11 }}>标的范围</span>}
              >
                <Input
                  readOnly
                  bordered={false}
                  style={{ background: 'transparent', paddingLeft: 0 }}
                />
              </Form.Item>

              <Form.Item<FieldType>
                name="reportDate"
                label={<span style={{ marginLeft: 11 }}>交易申报时间</span>}
              >
                <Input
                  readOnly
                  bordered={false}
                  style={{ background: 'transparent', paddingLeft: 0 }}
                />
              </Form.Item>
            </div>
          </Spin>
        ) : (
          <div>
            <Form.Item<FieldType> label={<span style={{ marginLeft: 11 }}>窗口名称</span>}>
              <Input
                value={editValue.scenarioName || '--'}
                readOnly
                bordered={false}
                style={{ background: 'transparent', paddingLeft: 0 }}
              />
            </Form.Item>
            <Form.Item<FieldType> label={<span style={{ marginLeft: 11 }}>交易单元</span>}>
              <Input
                value={editValue.stationName || '--'}
                readOnly
                bordered={false}
                style={{ background: 'transparent', paddingLeft: 0 }}
              />
            </Form.Item>
            <Form.Item<FieldType> label={<span style={{ marginLeft: 11 }}>标的范围</span>}>
              <Input
                value={editValue.markDate || '--'}
                readOnly
                bordered={false}
                style={{ background: 'transparent', paddingLeft: 0 }}
              />
            </Form.Item>

            <Form.Item<FieldType> label={<span style={{ marginLeft: 11 }}>交易申报时间</span>}>
              <Input
                value={editValue.reportTime || '--'}
                readOnly
                bordered={false}
                style={{ background: 'transparent', paddingLeft: 0 }}
              />
            </Form.Item>
          </div>
        )}

        <Form.Item
          name="priceRange"
          label={<span>价格范围</span>}
          rules={[{ required: true, message: '价格范围必填!' }]}
        >
          <Row>
            <Col span={11}>
              <Form.Item<FieldType>
                name="minPrice"
                noStyle
                rules={[{ validator: validateNoSpaces('最小价格范围') }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
            <Col span={2} style={{ textAlign: 'center' }}>
              -
            </Col>
            <Col span={11}>
              <Form.Item<FieldType>
                name="maxPrice"
                noStyle
                rules={[{ validator: validateNoSpaces('最大价格范围') }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item
          name="quantityRange"
          label={<span>电量范围</span>}
          rules={[{ required: true, message: '电量范围必填!' }]}
        >
          <Row>
            <Col span={11}>
              <Form.Item<FieldType>
                name="minQuantity"
                noStyle
                rules={[{ validator: validateNoSpaces('最小电量范围') }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
            <Col span={2} style={{ textAlign: 'center' }}>
              -
            </Col>
            <Col span={11}>
              <Form.Item<FieldType>
                name="maxQuantity"
                noStyle
                rules={[{ validator: validateNoSpaces('最大电量范围') }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item<FieldType>
          label="摘牌总量"
          name="totalDelisted"
          rules={[{ required: true, message: '摘牌总量必填!' }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </div>
    );
  };

  return (
    <div className={styles.molContent}>
      {state.addVisible && (
        <TJModel
          width={520}
          title={modelTitle}
          onCancel={onCancelAddVisible}
          visible={state.addVisible}
          footer={false}
        >
          <Form
            form={form}
            name="AE"
            labelAlign="left"
            {...formItemLayout}
            onFinish={handleFinish}
            autoComplete="off"
            onValuesChange={(changedValues, allValues) => {
              const { minPrice, maxPrice, minQuantity, maxQuantity } = allValues;
              if (!minPrice || !maxPrice) {
                if (allValues.priceRange !== null) {
                  form.setFieldsValue({ priceRange: null });
                }
              } else {
                const newPriceRange = [minPrice, maxPrice];
                if (
                  !allValues.priceRange ||
                  allValues.priceRange[0] !== newPriceRange[0] ||
                  allValues.priceRange[1] !== newPriceRange[1]
                ) {
                  form.setFieldsValue({ priceRange: newPriceRange });
                }
              }
              if (!minQuantity || !maxQuantity) {
                if (allValues.quantityRange !== null) {
                  form.setFieldsValue({ quantityRange: null });
                }
              } else {
                const newQuantityRange = [minQuantity, maxQuantity];
                if (
                  !allValues.quantityRange ||
                  allValues.quantityRange[0] !== newQuantityRange[0] ||
                  allValues.quantityRange[1] !== newQuantityRange[1]
                ) {
                  form.setFieldsValue({ quantityRange: newQuantityRange });
                }
              }
            }}
          >
            {Content()}
            <Row style={{ marginTop: 10, justifyContent: 'end' }}>
              <div>
                <Button onClick={onCancelAddVisible}>取消</Button>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </div>
            </Row>
          </Form>
        </TJModel>
      )}
    </div>
  );
};

export default connect(({ global, ListingTransactionDeclaration }: any) => ({
  buttonPermissions: global.configure.buttonPermissions,
  list: ListingTransactionDeclaration.list,
  windowConfigs: ListingTransactionDeclaration.windowConfigs,
  configLoading: ListingTransactionDeclaration.configLoading,
}))(Plan);
